package com.mugui.base.client.net.classutil;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import com.mugui.base.base.ApplicationContext;

public class DataSave {
	public static List<Class<?>> CLASS_LIST = null;
	public static ConcurrentHashMap<Class<?>, Boolean> map = new ConcurrentHashMap<>();
	public static ApplicationContext context;
	public static String APP_PATH = APP_PATH(DataSave.class);

	public static String APP_PATH(Class<?> class1) {
		System.setProperty("sun.jnu.encoding", "utf-8");
		APP_PATH = class1.getProtectionDomain().getCodeSource().getLocation().getFile();
		try {
			APP_PATH = URLDecoder.decode(new File(APP_PATH).getParent(), "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		System.setProperty("jna.encoding", "GBK");
		return APP_PATH;
	}

	public static List<Class<?>> initClassList(Class<?> name) {
		if (map.get(name) != null)
			return CLASS_LIST;
		map.put(name, true);
//		CLASS_LIST = handle(name);
		CLASS_LIST = new ArrayList<Class<?>>();
		ApplicationContext applicationContext = (ApplicationContext) DataSave.context;
		for (String type : applicationContext.getBeanDefinitionNames()) {
			CLASS_LIST.add(applicationContext.getType(type));
		}
//		CLASS_LIST.addAll(handle(DataSave.class));
		return CLASS_LIST;
	}

	public static List<Class<?>> handle(Class<?> name) {
		URL url = name.getClassLoader().getResource(name.getName().replaceAll("[.]", "/") + ".class");
		String type = url.getProtocol();
		List<Class<?>> list = new ArrayList<>();
		if (type.equals("file")) {
			list.addAll(ClassTool.getClassNameByFile(new File(url.getPath()).getParentFile(), null, name.getName()));
		} else if (type.equals("jar")) {
			list.addAll(ClassTool.getClassNameByJar(url.getPath(), name.getName()));
		}
		return list;
	}
}
